package com.yulongtian.interviewWorks.day20221110;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/find-majority-element-lcci/?favorite=xb9lfcwi
 *
 * @author yulongTian
 * @create 2022-11-10 15:15
 */
public class Test01 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        System.out.println(majorityElement(nums));
    }


    public static int majorityElement(int[] nums) {
        int candidate = -1;
        int count = 0;
        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            if (num == candidate) {
                count++;
            } else {
                count--;
            }
        }
        count = 0;
        int length = nums.length;
        for (int num : nums) {
            if (num == candidate) {
                count++;
            }
        }
        return count * 2 > length ? candidate : -1;
    }

}
